import { Subject } from "../subject";
import Utils from "../utils";

export default class DomLayerManager {
    static nodes: DomLayerNode[] = [];
    static _gameCanvasCom: cc.Canvas = null;
    static get gameCanvasCom(): cc.Canvas {
        if (!DomLayerManager._gameCanvasCom) {
            DomLayerManager._gameCanvasCom = Utils.game.getComponent(cc.Canvas);
        }
        return DomLayerManager._gameCanvasCom;
    }
    static domFollowNode(dom: any, node: any) {
        var wph = document.body.clientWidth / Utils.game.node.width;
        var hph = document.body.clientHeight / Utils.game.node.height;
        var ph = 1;
        if (DomLayerManager.gameCanvasCom.fitHeight && DomLayerManager.gameCanvasCom.fitWidth) {
            ph = Math.min(wph, hph);
        }
        else if (DomLayerManager.gameCanvasCom.fitWidth) {
            ph = wph;
        }
        else if (DomLayerManager.gameCanvasCom.fitHeight) {
            ph = hph;
        }
        // console.log(wph, hph, ph);
        var origin = { //网页中点。
            x: document.body.clientWidth / 2,
            y: document.body.clientHeight / 2
        };

        var pos = Utils.game.node.convertToNodeSpaceAR(node.convertToWorldSpaceAR(cc.Vec2.ZERO));
        var width = node.width * node.scale * node.parent.scale * ph;
        var height = node.height * node.scale * node.parent.scale * ph;
        dom.style.width = width + "px";
        dom.style.height = height + "px";
        dom.style.opacity = node.opacity / 255;
        dom.style.left = origin.x + pos.x * ph - width / 2 + "px";
        dom.style.top = origin.y - pos.y * ph - height / 2 + "px";
    }
};

export abstract class DomLayerNode extends cc.Component {
    ele: HTMLElement = null;
    abstract createElement(): void;
    abstract destroyElement(): void;

    protected onLoad(): void {
        this.createElement();
    }
    protected onDisable(): void {
        this.ele.style.display = "none";
    }
    protected onEnable(): void {
        this.ele.style.display = "";
    }
    protected onDestroy(): void {
        let ind = DomLayerManager.nodes.findIndex(ele => ele == this);
        if (ind !== -1) {
            DomLayerManager.nodes.splice(ind, 1);
        }

        this.destroyElement();
    }
    constructor() {
        super();
        DomLayerManager.nodes.push(this);
    }

    update(dt: number) {
        if (this.ele) {
            DomLayerManager.domFollowNode(this.ele, this.node);
        }
    }
};

export abstract class DomLayer extends Subject {
    ele: HTMLElement = null;
    abstract onLoad(): void;
    abstract onDestroy(): void;
    abstract update(dt: number): void;

    destroy(){
        if (this.ele) {
            this.ele.remove();
            this.ele = null;
        }
        this.onDestroy();
        this.emit("destroy");
    }
}